//
//  NSString+Founction.m
//  StaffTax
//
//  Created by 侯伟 on 2020/3/23.
//  Copyright © 2020 侯伟. All rights reserved.
//

#import "NSString+Founction.h"


@implementation NSString (Founction)

//字符串转字典
- (NSDictionary *)JsonStringWithDictionary{
    if (!self) {
        return nil;
    }
    
    NSData *jsonData = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if(err) {
#ifdef DEBUG
        NSLog(@"json解析失败：%@",err);
#endif
        return nil;
    }
    return dic;
}


-(NSString *)getCnMoneyByString{
    // 设置数据格式
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    //NSLocale的意义是将货币信息、标点符号、书写顺序等进行包装，如果app仅用于中国区应用，为了保证当用户修改语言环境时app显示语言一致，则需要设置NSLocal（不常用）
    numberFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    // 全拼格式
    [numberFormatter setNumberStyle:NSNumberFormatterSpellOutStyle];
    // 小数点后最少位数
    [numberFormatter setMinimumFractionDigits:0];
    // 小数点后最多位数
    [numberFormatter setMaximumFractionDigits:2];
    // 整数最大位数
    [numberFormatter setMaximumIntegerDigits:10];

    [numberFormatter setFormatterBehavior:NSNumberFormatterBehaviorDefault];
    
    
    NSString *formattedNumberString = [numberFormatter stringFromNumber:[NSNumber numberWithDouble:[self doubleValue]]];
    if([formattedNumberString hasPrefix:@"十"]){
        formattedNumberString = [formattedNumberString stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:@"壹拾"];
    }
    //通过NSNumberFormatter转换为大写的数字格式 eg:一千二百三十四//替换大写数字转为金额
    formattedNumberString = [formattedNumberString stringByReplacingOccurrencesOfString:@"一" withString:@"壹"];
    formattedNumberString = [formattedNumberString stringByReplacingOccurrencesOfString:@"二" withString:@"贰"];
    formattedNumberString = [formattedNumberString stringByReplacingOccurrencesOfString:@"三" withString:@"叁"];
    formattedNumberString = [formattedNumberString stringByReplacingOccurrencesOfString:@"四" withString:@"肆"];
    formattedNumberString = [formattedNumberString stringByReplacingOccurrencesOfString:@"五" withString:@"伍"];
    formattedNumberString = [formattedNumberString stringByReplacingOccurrencesOfString:@"六" withString:@"陆"];
    formattedNumberString = [formattedNumberString stringByReplacingOccurrencesOfString:@"七" withString:@"柒"];
    formattedNumberString = [formattedNumberString stringByReplacingOccurrencesOfString:@"八" withString:@"捌"];
    formattedNumberString = [formattedNumberString stringByReplacingOccurrencesOfString:@"九" withString:@"玖"];
    formattedNumberString = [formattedNumberString stringByReplacingOccurrencesOfString:@"〇" withString:@"零"];
    formattedNumberString = [formattedNumberString stringByReplacingOccurrencesOfString:@"千" withString:@"仟"];
    formattedNumberString = [formattedNumberString stringByReplacingOccurrencesOfString:@"百" withString:@"佰"];
    formattedNumberString = [formattedNumberString stringByReplacingOccurrencesOfString:@"十" withString:@"拾"];// 对小数点后部分单独处理
    // rangeOfString 前面的参数是要被搜索的字符串，后面的是要搜索的字符
    if ([formattedNumberString rangeOfString:@"点"].length>0){
        // 将“点”分割的字符串转换成数组，这个数组有两个元素，分别是小数点前和小数点后
        NSArray* arr = [formattedNumberString componentsSeparatedByString:@"点"];
        // 如果对一不可变对象复制，copy是指针复制（浅拷贝）和mutableCopy就是对象复制（深拷贝）。如果是对可变对象复制，都是深拷贝，但是copy返回的对象是不可变的。
        // 这里指的是深拷贝
        NSMutableString* lastStr = [[arr lastObject] mutableCopy];NSLog(@"---%@---长度%ld", lastStr, lastStr.length);
        if (lastStr.length>=2){
            // 在最后加上“分”
            [lastStr insertString:@"分" atIndex:lastStr.length];
        }
        if (![[lastStr substringWithRange:NSMakeRange(0, 1)] isEqualToString:@"零"]){
            // 在小数点后第一位后边加上“角”
            [lastStr insertString:@"角" atIndex:1];
            
        }
        // 在小数点左边加上“元”
        formattedNumberString = [[arr firstObject] stringByAppendingFormat:@"元%@",lastStr];
        
    }else// 如果没有小数点
    {
        formattedNumberString = [formattedNumberString stringByAppendingString:@"圆整"];
        
    }
    return formattedNumberString;
    
}


// 自定义正数格式(金额的格式转化) 94,862.57 前缀可在所需地方随意添加
+ (NSString *)stringConvertToMoneyFormatWithNumber:(double)number {
    
    if(number == 0){
        return @"0";
    }
    
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.positiveFormat = @"###,##0.00"; // 正数格式
    formatter.numberStyle = NSNumberFormatterCurrencyStyle;
    [formatter setMaximumFractionDigits:2];
    // 注意传入参数的数据长度，可用double
    NSString *money = [formatter stringFromNumber:@(number)];
    return money;
}

// 自定义正数格式(金额的格式转化) 94,862.57 前缀可在所需地方随意添加
+ (NSString *)stringConvertToMoneyFormatWithNumberStr:(NSString*)numberStr {
    
    if(!numberStr.length || [numberStr doubleValue] == 0){
        return @"0";
    }
    
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    NSNumber* number = [formatter numberFromString:numberStr];
    formatter.positiveFormat = @"###,##0.00"; // 正数格式
    [formatter setMaximumFractionDigits:2];
    formatter.numberStyle = NSNumberFormatterCurrencyStyle;
    // 注意传入参数的数据长度，可用double
    NSString *money = [formatter stringFromNumber:number];
    return money;
}

//高精度显示
+ (NSString*)convterNumberToHighPrecision:(double)number{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    numberFormatter.numberStyle = kCFNumberFormatterNoStyle;
    [numberFormatter setMinimumIntegerDigits:1];
    [numberFormatter setMaximumFractionDigits:6];
    [numberFormatter setMinimumFractionDigits:2];
    
    return [numberFormatter stringFromNumber:@(number)];
}
//高精度显示
+ (NSString*)convterStringToHighPrecision:(NSString*)numberStr{
    
    double number = [numberStr doubleValue];
    
    return [NSString convterNumberToHighPrecision:number];
}


/**
 * 金额的格式转化
 * str : 金额的字符串
 * numberStyle : 金额转换的格式
 * return  NSString : 转化后的金额格式字符串
 */
+ (NSString *)stringChangeMoneyWithStr:(NSString *)str numberStyle:(NSNumberFormatterStyle)numberStyle {
    
    // 判断是否null 若是赋值为0 防止崩溃
    if (([str isEqual:[NSNull null]] ||  !str.length)) {
        str = @"";
    }
    
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init];
    formatter.numberStyle = numberStyle;
    // 注意传入参数的数据长度，可用double
    NSString *money = [formatter stringFromNumber:[NSNumber numberWithDouble:[str doubleValue]]];
    
    return money;
}



//邮箱地址的正则表达式
-(BOOL)isValidateEmail{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
//    NSString *emailRegex = @"^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:self];
}

//判断手机号是否正确
-(BOOL)isValidateMobile{
    
    // 第一个数字是 1  必须是 11 位  必须全部是数字
   if ([[self substringToIndex:1] isEqualToString:@"1"]  && self.length == 11 && [self  isPureInt]) {
       return YES;
   }else{
       
       return NO;
   }
    
}


//判断是否 整数
- (BOOL)isPureInt{
    
    NSScanner* scan = [NSScanner scannerWithString:self];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
    
}
//判断是否小数
- (BOOL)isPureFloat{
    
    NSScanner* scan = [NSScanner scannerWithString:self];
    float val;
    return[scan scanFloat:&val] && [scan isAtEnd];
    
}
//判断是否数字
-(BOOL)isPureNunber{
    if ([self isPureInt] || [self isPureFloat]) {
        return YES;
    }else{
        return NO;
    }
}


- (BOOL)isFixedTelephone {
    
    /**
     * 大陆地区固话及小灵通
     * 区号：010,020,021,022,023,024,025,027,028,029
     * 号码：七位或八位
     */
    
    NSString * FT = @"^(0[0-9]{2})-\\d{7,8}$|^(0[0-9]{3}-(\\d{7,8}))$";
    
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", FT];
    
    return [regextestcm evaluateWithObject:self];
    
}

/**限制公司名称只能是纯汉字或纯英文*/
-(BOOL)isValidateCompanyname{

    if([self containsString:@"("] || [self containsString:@")"]) {
        
        return NO;
        
    }
    
    NSString *emailRegex = @"^[\\u4e00-\\u9fa5a-zA-Z（）《》.]+$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:self];
}

/**限制法人*/
-(BOOL)isLegalPersonName{
    
    NSString *emailRegex = @"^[\\u4e00-\\u9fa5a-zA-Z]+$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:self];
}



-(NSString*)rs_add:(NSString*)str{
    NSString* selfStr;
    if (![self isPureNunber]) {
        selfStr = @"0";
    }else{
        selfStr = self;
    }
    if (![str isPureNunber]) {
        str = @"0";
    }
    
    NSDecimalNumber *oneDecimalNumber = [[NSDecimalNumber alloc] initWithString:selfStr];

    NSDecimalNumber *twoDecimalNumber = [[NSDecimalNumber alloc] initWithString:str];
    
    NSDecimalNumber *addRes = [oneDecimalNumber decimalNumberByAdding:twoDecimalNumber];
    
    return [NSString  stringWithFormat:@"%@",addRes];
    
//    https://www.jianshu.com/p/f53c62bf1657
}

-(NSString*)rs_minus:(NSString*)str{
    NSString* selfStr;
    if (![self isPureNunber]) {
        selfStr = @"0";
    }else{
        selfStr = self;
    }
    if (![str isPureNunber]) {
        str = @"0";
    }
    
    NSDecimalNumber *oneDecimalNumber = [[NSDecimalNumber alloc] initWithString:selfStr];

    NSDecimalNumber *twoDecimalNumber = [[NSDecimalNumber alloc] initWithString:str];
    
    NSDecimalNumber *subtractRes = [oneDecimalNumber decimalNumberBySubtracting:twoDecimalNumber];
    
    return [NSString  stringWithFormat:@"%@",subtractRes];
}

-(NSString*)rs_multiply:(NSString*)str{
    
    NSString* selfStr;
    if (![self isPureNunber]) {
        selfStr = @"0";
    }else{
        selfStr = self;
    }
    if (![str isPureNunber]) {
        str = @"0";
    }
    
    NSDecimalNumber *oneDecimalNumber = [[NSDecimalNumber alloc] initWithString:selfStr];
    
    NSDecimalNumber *twoDecimalNumber = [[NSDecimalNumber alloc] initWithString:str];
    
    NSDecimalNumber *multiplyingRes = [oneDecimalNumber decimalNumberByMultiplyingBy:twoDecimalNumber];
    
    return [NSString  stringWithFormat:@"%@",multiplyingRes];
}

-(NSString*)rs_divide:(NSString*)str{
    
    NSString* selfStr;
    if (![self isPureNunber]) {
        selfStr = @"0";
    }else{
        selfStr = self;
    }
    if (![str isPureNunber]) {
        [Toast toast:@"除数不能为0"];
        return nil;
    }
    
    NSDecimalNumber *oneDecimalNumber = [[NSDecimalNumber alloc] initWithString:selfStr];
    
    NSDecimalNumber *twoDecimalNumber = [[NSDecimalNumber alloc] initWithString:str];
    
    NSDecimalNumber *divideRes = [oneDecimalNumber decimalNumberByDividingBy:twoDecimalNumber];

    return [NSString  stringWithFormat:@"%@",divideRes];
}

-(NSInteger)rs_compare:(NSString*)str{
    NSDecimalNumber *num1 = [NSDecimalNumber decimalNumberWithString:self];

    NSDecimalNumber *num2 = [NSDecimalNumber decimalNumberWithString:str];
    
    return [num1 compare:num2];

}

-(NSString* )getNumberFromStr{
    
     NSCharacterSet* nonDigits =[[NSCharacterSet decimalDigitCharacterSet] invertedSet];
     return  [self stringByTrimmingCharactersInSet:nonDigits] ;

}


+(BOOL)dateTimeDifferenceWithStartTime:(NSString *)startTime endTime:(NSString *)endTime{
    
    NSDateFormatter *dateFomatter = [[NSDateFormatter alloc] init];
    dateFomatter.dateFormat = @"yyyy-MM-dd HH:mm";
    
    // 开始时间data格式
    NSDate* nowDate = [dateFomatter dateFromString:startTime];
    // 截止时间data格式
    NSDate *expireDate = [dateFomatter dateFromString:endTime];
    // 当前日历
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // 需要对比的时间数据
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth
    | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    // 对比时间差
    NSDateComponents *dateCom = [calendar components:unit fromDate:nowDate toDate:expireDate options:0];
    
    // 伪代码
//    年差额 = dateCom.year, 月差额 = dateCom.month, 日差额 = dateCom.day, 小时差额 = dateCom.hour, 分钟差额 = dateCom.minute, 秒差额 = dateCom.second
    
    RSLOG(@"----------------888---------------------**%ld==---**%ld---**%ld---**%ld---**%ld",dateCom.year,dateCom.month,dateCom.day,dateCom.hour,dateCom.minute);
    
    if (dateCom.year == 0 && dateCom.month == 0 && dateCom.day == 0 && dateCom.hour == 0 && dateCom.minute == 0) {
        return YES;
    }
    
    if (dateCom.year <0 || dateCom.month <0 || dateCom.day <0 || dateCom.hour <0 || dateCom.minute <0) {
        return NO;
    }else{
        return YES;
    }
    
  
}

+(NSString*)currentTime:(NSString*)fromat{
    
    NSDate *date = [NSDate date];
    
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateFormat:fromat];
    
    NSString * currentTimeString = [formatter stringFromDate:date];
    
    return  currentTimeString;
}

+(NSString*)timeTransformTime:(NSString*)time fromFormat:(NSString*)fromFormat toFormat:(NSString*)toFormat{

    NSDateFormatter *fromFormatter = [[NSDateFormatter alloc] init];
    [fromFormatter setDateFormat:fromFormat];
    
    NSDate *date = [fromFormatter dateFromString:time];
    
    NSDateFormatter *toFormatter = [[NSDateFormatter alloc] init];
    [toFormatter setDateFormat:toFormat];
    
    return  [toFormatter stringFromDate:date];
}


+(NSString*)chineseNumbers:(NSInteger)number{
    
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.positiveFormat = @"###"; // 正数格式
    formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    [formatter setMaximumFractionDigits:0];
    formatter.numberStyle = kCFNumberFormatterSpellOutStyle;
    
    return  [formatter stringFromNumber:@(number)];
}


+ (double)timeStringToFloat:(NSString*)timeStr{
    
    //转data
    NSDate* date = [self stringToDate:timeStr formatter:@"yyyy-MM-dd"];//获取当前时间0秒后的时间
    NSTimeInterval time=[date timeIntervalSince1970];// *1000 是精确到毫秒，不乘就是精确到秒
    return time;

}

// 字符串转date
+(NSDate*)stringToDate:(NSString*)timeString formatter:(NSString*)formatterStr{
//    NSString *dateString = @"2015-06-26 08:08:08";
     //设置转换格式
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
//    [formatter setTimeZone:[NSTimeZone timeZoneWithName:@"America/English"]];
    [formatter setDateFormat:formatterStr];
    //NSString转NSDate
    return [formatter dateFromString:timeString];
}
@end
